package org.jeecg.modules.trade.service.impl;

import com.alibaba.druid.sql.visitor.functions.If;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bitget.openapi.common.client.BitgetRestClient;
import com.bitget.openapi.common.domain.ClientParameter;
import com.bitget.openapi.common.enums.SupportedLocaleEnum;
import com.bitget.openapi.common.enums.mix.MixOrderTypeEnum;
import com.bitget.openapi.common.enums.mix.MixSideEnum;
import com.bitget.openapi.common.enums.spot.ForceEnum;
import com.bitget.openapi.dto.request.mix.MixPlaceOrderReq;
import com.bitget.openapi.dto.response.ResponseResult;
import freemarker.core.Environment;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.base.trade.entity.TvcTradeAccount;
import org.jeecg.modules.base.trade.entity.TvcTradeDocking;
import org.jeecg.modules.trade.mapper.TvcTradeDockingMapper;
import org.jeecg.modules.trade.service.ITvcTradeAccountService;
import org.jeecg.modules.trade.service.ITvcTradeDockingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Arrays;

/**
 * @Description: tvc_trade_docking
 * @Author: jeecg-boot
 * @Date: 2023-09-07
 * @Version: V1.0
 */
@Service
@Slf4j
public class TvcTradeDockingServiceImpl extends ServiceImpl<TvcTradeDockingMapper, TvcTradeDocking> implements ITvcTradeDockingService {
    private static String symbol = "XRPUSDT_UMCBL";
    private static String marginCoin = "USDT";
    private static String startTime = "1629113823000";
    private static String endTime = "1629513368000";
    private static String lastEndId = "0";
    private static int pageSize = 20;
    /**
     * The user apiKey is replaced with his own
     */
    private final String apiKey = "bg_e3c7836913b341ab4b2e4f3db3f57749";
    /**
     * The user's secretKey is replaced with his own
     */
    private final String secretKey = "35c9ad04ea9c7dc77fc099442eb45eccd2c6e3cbe3dcb58655dca74d2f8798a7";
    /**
     * Replace the password with your own
     */
    private final String passphrase = "13850712780lz";
    /**
     * Bitget open api root path
     */
    //
    private final String baseUrl = "https://api.bitget.com";
    @Autowired
    private Environment environment;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private ITvcTradeAccountService accountService;

    @Override
    public void placeOrder(TvcTradeDocking trade) {
        log.info("下单请求参数:{}", trade.toString());
        // 判断环境prod
        // 获取当前的运行环境
        String[] activeProfiles = environment.getCustomAttributeNames();
        // 判断当前激活的profile
        if (Arrays.asList(activeProfiles).contains("prod")) {
            // 在生产环境中执行判断请求路径是否来自tv
            String requestUrl = request.getRequestURI().toString();
            if (!requestUrl.contains("https://www.tradingview.com/")) {
                //外来请求 记录交易日志
                log.info("非法请求:{}", requestUrl);
            }
        }
        //trade.getTrdateId()对解密
        TvcTradeAccount account = accountService.getById(trade.getTrdateId());
        //account解密
        ClientParameter parameter = ClientParameter.builder().apiKey(account.getApiKey()).secretKey(account.getSercretKey()).passphrase(account.getPassword()).baseUrl(baseUrl)
                .locale(SupportedLocaleEnum.ZH_CN.getName()).build();
        String side = "";
        if (trade.getAction().equals(MixSideEnum.SELL) || trade.getAction().equals(MixSideEnum.FLAT)) {
            if (trade.getMarketPosition().equals(MixSideEnum.LONG)) {
                side = MixSideEnum.CLOSE_LONG.getSide();
            }
            if (trade.getMarketPosition().equals(MixSideEnum.SHORT)) {
                side = MixSideEnum.CLOSE_SHORT.getSide();
            }
        } else if (trade.getAction().equals(MixSideEnum.BUY)) {
            if (trade.getMarketPosition().equals(MixSideEnum.LONG)) {
                side = MixSideEnum.OPEN_LONG.getSide();
            }
            if (trade.getMarketPosition().equals(MixSideEnum.SHORT)) {
                side = MixSideEnum.OPEN_SHORT.getSide();
            }
        } else {
            //缺失Action
        }
        MixPlaceOrderReq req = MixPlaceOrderReq.builder()
                .clientOid("RFIut#" + System.currentTimeMillis())
                .symbol(trade.getSymbol())
                .price(new BigDecimal(trade.getPrice()))
                .size(new BigDecimal(trade.getMarketPositionSize()))
                .marginCoin(marginCoin)
                .side(side)
                .timeInForceValue(ForceEnum.NORMAL.getCode())
                .orderType(trade.getOrdType())
                .build();
        BitgetRestClient bitgetRestClient = BitgetRestClient.builder().configuration(parameter).build();
        ResponseResult result = null;
        try {
            result = bitgetRestClient.mix().bitget().order().placeOrder(req);
        } catch (IOException e) {
            e.printStackTrace();
        }
        baseMapper.insert(trade);
        log.info("下单返回数据:{}", JSON.toJSONString(result));
        System.out.println(JSON.toJSONString(result));
        //记录返回交易请求
    }
}
